import { reactive, ref, watch, onActivated, onDeactivated, onMounted, nextTick } from 'vue'

interface IPager {
  pageNo: number
  pageSize: number
  total: number
}

interface IFetchOptions {
  api: (params) => Promise<any>
  originalResp?: boolean // 是否需要返回初始的response
  autoSearch?: boolean // 是否需要默认发起请求(缓存页面中)
  pagination?: IPager
  formatFilters?: (filters: Record<string, any>) => Record<string, any>
  onSuccess?: (data: any[]) => void
  [key: string]: any
}

export default function useFetchTable<T = Record<string, unknown>>(options: IFetchOptions) {
  let mounted = false
  const autoSearch = options?.autoSearch ?? true
  const showSearch = ref(true) // 显示搜索条件
  const loading = ref(false) // 列表的加载中
  const filters = reactive<Record<string, any>>({}) // 筛选框数据
  const list = ref<T[]>([]) // 列表的数据
  const page = ref({
    pageNo: 1,
    pageSize: 10,
    total: 0
  }) // 分页数据

  const onFiltersChangeByKey = (key: string, value: unknown) => {
    console.log(key, '  ', value)
    console.log('filters: ', filters)
    filters[key] = value
  }

  const getParams = (sortData?: Record<string, any>) => {
    const { pageNo, pageSize } = page.value
    return {
      ...(sortData ?? {}),
      ...(options?.formatFilters?.(filters) ?? filters),
      pageNo,
      pageSize
    }
  }

  const getList = async (sortData: Object = {}) => {
    // console.log('sortData：', sortData)
    try {
      loading.value = true
      const params = getParams(sortData ?? {})
      console.log(params)
      const resp = await options.api(params)
      list.value = resp?.list ?? []
      page.value.total = resp.total
      options?.onSuccess?.(options?.originalResp ? resp : list.value)
    } finally {
      loading.value = false
    }
  }

  const onSearch = () => {
    page.value.pageNo = 1
    getList()
  }

  // 监听分页器
  // watch([() => page.value.pageNo, () => page.value.pageSize], () => {
  //   getList()
  // })

  onMounted(() => {
    nextTick(() => {
      mounted = true
    })
  })

  onActivated(() => {
    if (mounted && autoSearch) getList()
    // if (mounted) getList()
  })

  onDeactivated(() => {})

  return { loading, showSearch, list, page, filters, onSearch, getList, onFiltersChangeByKey }
}
